package io.renren.modules.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.pms.dao.GoodsInfoDao;
import io.renren.modules.pms.dao.GoodsStockDao;
import io.renren.common.entity.GoodsInfoEntity;
import io.renren.modules.pms.dto.GoodsStockRecordDTO;
import io.renren.modules.pms.entity.GoodsStockEntity;
import io.renren.modules.pms.vo.GoodsStockRecordVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.pms.dao.GoodsStockRecordDao;
import io.renren.modules.pms.entity.GoodsStockRecordEntity;
import io.renren.modules.pms.service.GoodsStockRecordService;
import org.springframework.transaction.annotation.Transactional;


@Service("goodsStockRecordService")
public class GoodsStockRecordServiceImpl extends ServiceImpl<GoodsStockRecordDao, GoodsStockRecordEntity> implements GoodsStockRecordService {


    @Autowired
    private GoodsInfoDao goodsInfoDao;
    @Autowired
    private GoodsStockRecordDao goodsStockRecordDao;
    @Autowired
    private GoodsStockDao goodsStockDao;

    private static final Logger logger = LoggerFactory.getLogger(GoodsStockRecordServiceImpl.class);

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsStockRecordEntity> page = this.page(
                new Query<GoodsStockRecordEntity>().getPage(params),
                new QueryWrapper<GoodsStockRecordEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGoodsStockRecord(GoodsStockRecordDTO goodsStockRecordDTO) {
        GoodsStockRecordEntity goodsStockRecord = ConvertUtils.sourceToTarget(goodsStockRecordDTO, GoodsStockRecordEntity.class);
        GoodsInfoEntity goodsInfo = goodsInfoDao.selectOne(new LambdaQueryWrapper<GoodsInfoEntity>()
                .eq(GoodsInfoEntity::getBarcode, goodsStockRecord.getBarcode()));
        if (goodsInfo == null){
            throw new RRException("商品条码不存在");
        }

        goodsStockRecord.setDeleteState(0);
        goodsStockRecord.setCreateTime(new Date());
        goodsStockRecordDao.insert(goodsStockRecord);

        /**
         * 更新或添加库存
         **/
        GoodsStockEntity goodsStockEntity = goodsStockDao.selectOne(new LambdaQueryWrapper<GoodsStockEntity>()
                .eq(GoodsStockEntity::getGoodsId, goodsInfo.getId()));
        if (goodsStockEntity == null){
            if (goodsStockRecord.getType() == 1) throw new RRException("库存不存在该商品");
            goodsStockEntity = new GoodsStockEntity();
            goodsStockEntity.setGoodsId(goodsInfo.getId());
            goodsStockEntity.setGoodsName(goodsStockRecord.getGoodsName());
            goodsStockEntity.setBarcode(goodsStockRecord.getBarcode());
            goodsStockEntity.setNum(goodsStockRecord.getNum());
            goodsStockEntity.setCreateTime(new Date());
            goodsStockDao.insert(goodsStockEntity);
        } else {
            if(goodsStockRecord.getType() == 0) {
                goodsStockEntity.setNum(goodsStockEntity.getNum() + goodsStockRecord.getNum());
            } else {
                if(goodsStockEntity.getNum() < goodsStockRecord.getNum()) throw new RRException("商品库存不足");
                goodsStockEntity.setNum(goodsStockEntity.getNum() - goodsStockRecord.getNum());
            }
            goodsStockEntity.setUpdateTime(new Date());
            goodsStockDao.updateById(goodsStockEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsStockRecord(GoodsStockRecordDTO goodsStockRecordDTO) {
        GoodsStockRecordEntity goodsStockRecord = ConvertUtils.sourceToTarget(goodsStockRecordDTO, GoodsStockRecordEntity.class);
        GoodsInfoEntity goodsInfo = goodsInfoDao.selectOne(new LambdaQueryWrapper<GoodsInfoEntity>()
                .eq(GoodsInfoEntity::getBarcode, goodsStockRecord.getBarcode()));
        if (goodsInfo == null){
            throw new RRException("商品条码不存在");
        }

        GoodsStockRecordEntity goodsStockRecordEntity = goodsStockRecordDao.
                selectOne(new LambdaQueryWrapper<GoodsStockRecordEntity>()
                        .eq(GoodsStockRecordEntity::getId, goodsStockRecord.getId()));
        goodsStockRecord.setUpdateTime(new Date());
        goodsStockRecordDao.updateById(goodsStockRecord);

        // 如果条码改变，更新对应商品库存
        int num = goodsStockRecord.getNum() - goodsStockRecordEntity.getNum();
        if (!goodsStockRecordEntity.getBarcode().equals(goodsStockRecord.getBarcode())) {
            GoodsInfoEntity goodsInfoEntity = goodsInfoDao.selectOne(new LambdaQueryWrapper<GoodsInfoEntity>()
                    .eq(GoodsInfoEntity::getBarcode, goodsStockRecordEntity.getBarcode()));
            GoodsStockEntity misenteredInventory = goodsStockDao.selectOne(new LambdaQueryWrapper<GoodsStockEntity>()
                    .eq(GoodsStockEntity::getGoodsId, goodsInfoEntity.getId()));
            if (goodsStockRecordEntity.getType() == 0) {
                misenteredInventory.setNum(misenteredInventory.getNum() - goodsStockRecordEntity.getNum());
            } else if (goodsStockRecordEntity.getType() == 1){
                misenteredInventory.setNum(misenteredInventory.getNum() + goodsStockRecordEntity.getNum());
            }
            goodsStockDao.updateById(misenteredInventory);
            num = goodsStockRecord.getNum();
        }

        /**
         * 更新库存
         **/
        GoodsStockEntity goodsStockEntity = goodsStockDao.selectOne(new LambdaQueryWrapper<GoodsStockEntity>()
                .eq(GoodsStockEntity::getGoodsId, goodsInfo.getId()));
        if (goodsStockEntity == null) throw new RRException("商品库存不存在该商品");
        if(goodsStockRecord.getType() == 0){
            if (goodsStockRecordEntity.getType() == 0 ||
                    !goodsStockRecordEntity.getBarcode().equals(goodsStockRecord.getBarcode())) {
                goodsStockEntity.setNum(goodsStockEntity.getNum() + num);
            } else {
                goodsStockEntity.setNum(goodsStockEntity.getNum() + goodsStockRecord.getNum() + goodsStockRecordEntity.getNum());
            }
        } else if (goodsStockRecord.getType() == 1){
            if (goodsStockEntity.getNum() < num) throw new RRException("商品库存不足");
            if (goodsStockRecordEntity.getType() == 1 ||
                    !goodsStockRecordEntity.getBarcode().equals(goodsStockRecord.getBarcode())) {
                goodsStockEntity.setNum(goodsStockEntity.getNum() - num);
            } else {
                if (goodsStockEntity.getNum() < (goodsStockRecord.getNum() + goodsStockRecordEntity.getNum())) throw new RRException("商品库存不足");
                goodsStockEntity.setNum(goodsStockEntity.getNum() - (goodsStockRecord.getNum() + goodsStockRecordEntity.getNum()));
            }
        }
        if (!goodsStockRecordEntity.getBarcode().equals(goodsStockRecord.getBarcode())) {
            goodsStockEntity.setBarcode(goodsStockRecord.getBarcode());
        }
        goodsStockEntity.setGoodsName(goodsStockRecord.getGoodsName());
        goodsStockEntity.setUpdateTime(new Date());
        goodsStockDao.updateById(goodsStockEntity);
    }

    @Override
    public List<GoodsStockRecordVo> getPurchaseDetails() {
        return ConvertUtils.sourceToTarget(goodsStockRecordDao.selectPurchase(), GoodsStockRecordVo.class);
    }

}
